import json
from typing import List, Dict

from model import Discipline, DisciplineLinkView, DisciplineNodeView, DisciplineCategoryView, DisciplineDataView, \
    DisciplineDetail


def get_discipline_view_objects(
        base_data: List[Discipline],
        detail_data: Dict[str, DisciplineDetail],
        coordinate_data: dict
) -> DisciplineDataView:
    nodes: List[DisciplineNodeView] = list()
    links: List[DisciplineLinkView] = list()
    category_set = set()
    categories = list()
    original_data = dict()

    for discipline in base_data:
        if discipline.name in detail_data:
            discipline.description = detail_data[discipline.name].description
            discipline.history = detail_data[discipline.name].history
            discipline.famous_works = detail_data[discipline.name].famous_works
        original_data[discipline.name] = discipline
        nodes.append(DisciplineNodeView(name=discipline.name, category=discipline.category,
                                        x=coordinate_data[discipline.name][0], y=coordinate_data[discipline.name][1]))
        category_set.add(discipline.category)
        if discipline.super_disciplines:
            links.append(DisciplineLinkView(source=discipline.super_disciplines[-1], target=discipline.name))
    for category in category_set:
        categories.append(DisciplineCategoryView(name=category))
    return DisciplineDataView(nodes=nodes, links=links, categories=categories, original_data=original_data)


def main():
    with open("../assets/base_data.json", 'r') as f:
        base_data = json.load(f)
        base_data = [Discipline.model_validate_json(d) for d in base_data]

    with open("../assets/detail_data.json", 'r') as f:
        detail_data = json.load(f)
        detail_data = {k: DisciplineDetail.model_validate_json(v) for k, v in detail_data.items()}

    with open("../assets/coordinate_data.json", 'r', encoding="utf-8") as f:
        coordinate_data = json.load(f)

    view_data = get_discipline_view_objects(base_data, detail_data, coordinate_data)
    json_str = view_data.model_dump_json()
    with open('../assets/view_data.json', 'w', encoding='utf-8') as f:
        f.write(json_str)


if __name__ == '__main__':
    main()
